//
//  ViewController.m
//  WKWebView之MessageHandler
//
//  Created by mingjun zhang on 2017/9/24.
//  Copyright © 2017年 mingjun zhang. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <WebKit/WebKit.h>
#import "HLAudioPlayer.h"

@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@property (strong, nonatomic) WKWebView  *webView;

@property (strong, nonatomic) UIProgressView  *progressView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone; //不延伸到 navigationBar 下面
    self.navigationController.navigationBar.translucent = NO; //这时会发现导航栏变灰了
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    
    [self creatNavigation];   //初始化导航栏
    [self initWebView];       //初始化webView
    [self initProgressView]; //初始化进度条
    
}

//初始化导航栏
-(void)creatNavigation{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"后退" style:UIBarButtonItemStyleDone target:self action:@selector(goback)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"前进" style:UIBarButtonItemStyleDone target:self action:@selector(gofarward)];

}

- (void)goback {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
}

- (void)gofarward {
    if ([self.webView canGoForward]) {
        [self.webView goForward];
    }
}


//初始化webView
-(void)initWebView{

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferences =  [[WKPreferences alloc] init]; // 设置偏好设置
    preferences.javaScriptCanOpenWindowsAutomatically = YES; // 在iOS上默认为NO，表示不能自动通过窗口打开
    preferences.minimumFontSize = 30.0; //默认为0
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 84) configuration:configuration];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    NSURL *path = [[NSBundle mainBundle] URLForResource:@"nihao" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
    
    // 添加KVO监听
    [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew  context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew  context:nil];
    [self.webView addObserver:self  forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"loading"]) {
        NSLog(@"loading");
    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"progress: %f", self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
    }
    
    // 加载完成
    if (!self.webView.loading) {
        // 手动调用JS代码
        // 每次页面完成都弹出来，大家可以在测试时再打开
        NSString *js = @"callJsAlert()";
        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"response: %@ error: %@", response, error);
            NSLog(@"call js alert by native");
        }];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.progressView.alpha = 0;
        }];
    }
}


- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"loading"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

//初始化进度条
-(void)initProgressView{
    
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor greenColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
    
}

#pragma private method -- 私有方法
//获取位置信息
-(void)getLocation{
    
    //给JS传参
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"浙江杭州西湖区骆家庄"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@-----%@",result,error);
    }];
    
    //获取JS变量的值
    NSString *jsStr2 = @"window.ctuapp_share_img";
    [self.webView evaluateJavaScript:jsStr2 completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@-----%@",result,error);
    }];
    
}

//改变背景颜色
-(void)changeBgColorWithParams:(NSArray*)params{
    if (![params isKindOfClass:[NSArray class]]) {
        return;
    }
    
    if (params.count < 4) {
        return;
    }
    CGFloat r = [params[0] floatValue];
    CGFloat g = [params[1] floatValue];
    CGFloat b = [params[2] floatValue];
    CGFloat a = [params[3] floatValue];
    
    self.view.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
    
}

//分享操作
- (void)shareWithParams:(NSDictionary *)params{
    
    if (![params isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSString *title = [params objectForKey:@"title"];
    NSString *content = [params objectForKey:@"content"];
    NSString *url = [params objectForKey:@"url"];
    
    //将要分享的结果返回给JS
    NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@-----%@",result,error);
        
    }];
    
}


//支付的操作
-(void)payMoneyWithParams:(NSDictionary*)params{
    if (![params isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    NSString *count = [params objectForKey:@"amount"];
    NSString *cahnnel = [params objectForKey:@"channel"];
    NSString *order = [params objectForKey:@"order_no"];
    NSString *subject = [params objectForKey:@"subject"];
    NSLog(@"%@---%@--%@---%@",count,cahnnel,order,subject);
    
  //将支付的结果返回给JS
    NSString *jsStr = [NSString stringWithFormat:@"payResult('%@')",@"支付成功"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result,error);
    }];
    
    
}


//摇一摇功能
-(void)shakeAction{
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
    [HLAudioPlayer playMusic:@"shake_sound_male.wav"];
}

//返回功能
- (void)goBack{
    if ([self.webView canGoBack]) {
       [self.webView goBack];
    }
}

//播放声音
- (void)playSound:(NSString *)fileName{
    if (![fileName isKindOfClass:[NSString class]]) {
        return;
    }
     [HLAudioPlayer playMusic:fileName];
}




#pragma WKScriptMessageHandler
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    NSLog(@"%@-----%@",message.body,message.name);
    if ([message.name isEqualToString:@"ScanAction"]) {
        NSLog(@"扫一扫");
    }else if ([message.name isEqualToString:@"Location"]) {
        [self getLocation];
    }else if ([message.name isEqualToString:@"Color"]) {
        [self changeBgColorWithParams:message.body];
    }else if ([message.name isEqualToString:@"Share"]) {
        [self shareWithParams:message.body];
    }else if ([message.name isEqualToString:@"Pay"]) {
        [self payMoneyWithParams:message.body];
    }else if ([message.name isEqualToString:@"Shake"]) {
        [self shakeAction];
    }else if ([message.name isEqualToString:@"GoBack"]) {
        [self goBack];
    }else if ([message.name isEqualToString:@"PlaySound"]) {
        [self playSound:message.body];
    }

}


#pragma ----- WKUIDelegate
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
         completionHandler();
    } ]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}



















- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    // 注入JS对象名称，当JS通过名称来调用时，我们可以在WKScriptMessageHandler代理中接收到
 
    // addScriptMessageHandler 很容易导致循环引用
    // 控制器 强引用了WKWebView,WKWebView copy(强引用了）configuration， configuration copy （强引用了）userContentController
    // userContentController 强引用了 self （控制器）
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ScanAction"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Pay"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"PlaySound"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 因此这里要记得移除handlers
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ScanAction"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Pay"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Shake"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"PlaySound"];
}



@end


